package com.teacher.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.mapper.*;
import com.teacher.pojo.dto.carpoolPost.*;
import com.teacher.pojo.dto.comment.CommentAddDto;
import com.teacher.pojo.dto.notice.NoticeAddDto;
import com.teacher.pojo.entity.*;
import com.teacher.mapper.CarpoolPostMapper;
import com.teacher.pojo.entity.CarpoolPost;
import com.teacher.pojo.vo.WxLoginVo;
import com.teacher.pojo.vo.carpoolPost.CarpoolPostInfo;
import com.teacher.pojo.vo.carpoolPost.CarpoolPostVo;
import com.teacher.service.ICarpoolPostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiangzhuohang
 * @since 2024-03-14
 */
@Service
public class CarpoolPostServiceImpl extends ServiceImpl<CarpoolPostMapper, CarpoolPost> implements ICarpoolPostService {
    @Autowired
    private CarpoolPostMapper carpoolPostMapper;

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Autowired
    private CommentServiceImpl commentService;

    @Autowired
    private NoticeServiceImpl noticeService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Override
    public IPage<CarpoolPostVo> getCarpoolPostPageData(CarpoolPostDto pageVo) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
//        System.out.println(userDetails.getUsername());
        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        IPage<CarpoolPostVo> carpoolPostPageData = carpoolPostMapper.getCarpoolPostPageData(page, pageVo);
        return carpoolPostPageData;
    }

    @Override
    public CommonResult addCarpoolPost(CarpoolPostAddDto dto) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        CarpoolPost carpoolPost = new CarpoolPost();
        carpoolPost.setOpenId(openid);
        BeanUtil.copyProperties(dto,carpoolPost);
        int insert = carpoolPostMapper.insert(carpoolPost);
        if (insert<1) {
            return CommonResult.failed("新增失败");
        }
        return CommonResult.success("新增成功");
    }

    @Override
    public CommonResult deleteCarpoolPost(List<Long> list) {
        int i = carpoolPostMapper.deleteBatchIds(list);
        if (i<1){
            return CommonResult.failed("删除失败");
        }
        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult updateCarpoolPost(CarpoolPostUpdateDto updateDto) {
        CarpoolPost carpoolPost = new CarpoolPost();
        BeanUtil.copyProperties(updateDto,carpoolPost);
        int i = carpoolPostMapper.updateById(carpoolPost);
        if (i<1){
            return CommonResult.failed("更新失败");
        }
        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult getCarpoolList(SelectCarpoolList selectCarpoolList) {
        QueryWrapper<CarpoolPost> carpoolPostQueryWrapper = new QueryWrapper<>();
        //状态
        if (ObjectUtil.isNotEmpty(selectCarpoolList.getCarpoolStatus())){
            carpoolPostQueryWrapper.lambda().eq(CarpoolPost::getCarpoolStatus,selectCarpoolList.getCarpoolStatus());
        }
        //出发地名称
        if (ObjectUtil.isNotEmpty(selectCarpoolList.getStartPoint())){
            carpoolPostQueryWrapper.lambda().eq(CarpoolPost::getStartPoint,selectCarpoolList.getStartPoint());
        }
        //目的地名称
        if (ObjectUtil.isNotEmpty(selectCarpoolList.getEndPoint())){
            carpoolPostQueryWrapper.lambda().eq(CarpoolPost::getEndPoint,selectCarpoolList.getEndPoint());
        }
        //出发最早时间 帖子的结束时间晚于搜索的开始时间
        if (ObjectUtil.isNotEmpty(selectCarpoolList.getStartTime())){
            carpoolPostQueryWrapper.lambda().ge(CarpoolPost::getEndTime,selectCarpoolList.getStartTime());
        }
        //出发最晚时间  并且帖子的开始时间早与搜索的结束时间
        if (ObjectUtil.isNotEmpty(selectCarpoolList.getEndTime())){
            carpoolPostQueryWrapper.lambda().le(CarpoolPost::getStartTime,selectCarpoolList.getEndTime());
        }

        //新建集合
        List<CarpoolPostVo> carpoolPostVos = null;
        List<CarpoolPost> carpoolPosts = carpoolPostMapper.selectList(carpoolPostQueryWrapper);
        return CommonResult.success(carpoolPosts);
    }

    @Override
    public CommonResult getCarpoolInfoById(Long id) {
        if (id == null){
            return CommonResult.failed("错误传参");
        }

        CarpoolPost carpoolPost = carpoolPostMapper.selectById(id);
        if (ObjectUtil.isEmpty(carpoolPost)){
            return CommonResult.failed("找不到该拼车信息,请联系管理员");
        }
        CarpoolPostInfo carpoolPostInfo = new CarpoolPostInfo();
        BeanUtil.copyProperties(carpoolPost,carpoolPostInfo);
        //是否有正在申请的拼车人
        if (ObjectUtil.isNotEmpty(carpoolPost.getPrepareMembersOpenId())) {
            List<WxLoginVo> prepareMembers = new ArrayList<>();
            List<String> memberOpenIds =  Arrays.asList(carpoolPost.getPrepareMembersOpenId().split(","));
            for (String openId : memberOpenIds){
                WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openId));
                if (ObjectUtil.isNotEmpty(wechatUser)){
                    WxLoginVo wxLoginVo = new WxLoginVo();
                    BeanUtil.copyProperties(wechatUser,wxLoginVo);
                    prepareMembers.add(wxLoginVo);
                }
            }
            carpoolPostInfo.setPrepareMembers(prepareMembers);
        }

        //是否有通过审核的拼车人
        if (ObjectUtil.isNotEmpty(carpoolPost.getRealMembersOpenId())) {
            List<WxLoginVo> realMembers = new ArrayList<>();
            List<String> memberOpenIds =  Arrays.asList(carpoolPost.getRealMembersOpenId().split(","));
            for (String openId : memberOpenIds){
                WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openId));
                if (ObjectUtil.isNotEmpty(wechatUser)){
                    WxLoginVo wxLoginVo = new WxLoginVo();
                    BeanUtil.copyProperties(wechatUser,wxLoginVo);
                    realMembers.add(wxLoginVo);
                }
            }
            carpoolPostInfo.setRealMembers(realMembers);
        }
        WechatUser ownUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, carpoolPost.getOpenId()));
        WxLoginVo wxLoginVo = new WxLoginVo();
        BeanUtil.copyProperties(ownUser,wxLoginVo);
        carpoolPostInfo.setOwnInfo(wxLoginVo);

        return CommonResult.success(carpoolPostInfo);
    }

    @Override
    public CommonResult requestCarpool(RequestCarpoolDto requestCarpoolDto) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        CarpoolPost carpoolPost = carpoolPostMapper.selectById(requestCarpoolDto.getId());
        if (StrUtil.containsAny(carpoolPost.getPrepareMembersOpenId(),openid) || StrUtil.containsAny(carpoolPost.getRealMembersOpenId(),openid)){
            return CommonResult.failed("重复申请");
        }
        if (carpoolPost.getPrepareMembersOpenId().equals("")){
            carpoolPost.setPrepareMembersOpenId(openid);
        }else {
            //拼接
            String prepareMembersOpenId = carpoolPost.getPrepareMembersOpenId();
            prepareMembersOpenId += ","+openid;
            carpoolPost.setPrepareMembersOpenId(prepareMembersOpenId);
        }

        int i = carpoolPostMapper.updateById(carpoolPost);
        if (i<1) {
            return CommonResult.failed("申请失败");
        }

        //发送者详细信息
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openid));

        //通知表
        NoticeAddDto noticeAddDto = new NoticeAddDto();
        noticeAddDto.setType("1");
        noticeAddDto.setAcceptOpenId(carpoolPost.getOpenId());
        noticeAddDto.setSendName(wechatUser.getName());
        noticeAddDto.setSendOpenId(wechatUser.getOpenId());
        noticeAddDto.setRelevanceId(carpoolPost.getId());
        noticeAddDto.setContent("申请成为你的同乘搭子");

        noticeService.addNotice(noticeAddDto);


        //异步调用微信小程序推送消息
        String content = "申请成为你的同乘搭子";
        noticeService.sendCarpoolMessage(carpoolPost.getOpenId(),carpoolPost.getId(),wechatUser.getName(),content);

        return CommonResult.success("申请成功");
    }

    @Override
    public CommonResult examineCarpoolPost(ExamineCarpoolPostDto dto) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        CarpoolPost carpoolPost = carpoolPostMapper.selectById(dto.getId());
        if (BeanUtil.isEmpty(carpoolPost)){
            return CommonResult.failed("同乘不存在");
        }

        //是否本人发起的拼车
        if (!carpoolPost.getOpenId().equals(openid)){
            return CommonResult.failed("不是本人发起的同乘");
        }


        //是否有此申请人
        if (!StrUtil.containsAny(carpoolPost.getPrepareMembersOpenId(),dto.getOpenId())){
            return CommonResult.failed("该同乘没有此申请人,请刷新");
        }

        //发起人信息
        WechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, openid));

        NoticeAddDto noticeAddDto = new NoticeAddDto();
        noticeAddDto.setType("2");
        noticeAddDto.setAcceptOpenId(dto.getOpenId());
        noticeAddDto.setSendName(wechatUser.getName());
        noticeAddDto.setSendOpenId(carpoolPost.getOpenId());
        noticeAddDto.setRelevanceId(carpoolPost.getId());
        switch (dto.getStatus()){
            //拒绝
            case 0:
                noticeAddDto.setContent("您的同乘申请被拒绝,原因:"+dto.getContent());
                noticeService.addNotice(noticeAddDto);
                noticeService.sendCarpoolRespondMessage(dto.getOpenId(),dto.getId(),"拒绝",wechatUser.getName());
                break;
            //同意
            case 1:
                //更新拼车贴通过申请的人员和拼车状态
                List<String> realMembers =  Arrays.asList(carpoolPost.getRealMembersOpenId().split(","));
                List<String> newRealMemberOpenIds = new ArrayList<>();
                newRealMemberOpenIds.addAll(realMembers);
                newRealMemberOpenIds.add(dto.getOpenId());
                if (newRealMemberOpenIds.get(0).equals("")){
                    newRealMemberOpenIds.remove(0);
                }
                String newRealMemberOpenId = String.join(",", newRealMemberOpenIds);
                carpoolPost.setRealMembersOpenId(newRealMemberOpenId);
                carpoolPost.setCarpoolStatus(1);

                //评价表新增
                //申请人信息
                WechatUser wechatUserB = wechatUserMapper.selectOne(new QueryWrapper<WechatUser>().lambda().eq(WechatUser::getOpenId, dto.getOpenId()));

                Boolean commentSuccess = commentService.createComment(wechatUser, wechatUserB, carpoolPost.getId(), carpoolPost.getEndTime());
                if (!commentSuccess){
                    log.error("评价表新建失败");
                }
                //通知表
                noticeAddDto.setContent("您的同乘申请已通过,发起人微信号:"+carpoolPost.getInformation());
                noticeService.addNotice(noticeAddDto);
                noticeService.sendCarpoolRespondMessage(dto.getOpenId(),dto.getId(),"通过",wechatUser.getName());
                break;
        }

        //不管拒绝还是同意，都是这样删除掉申请列表中的此人
//        List<String> delete = new ArrayList<>();
//        delete.add(dto.getOpenId());
        List<String> preMemberOpenIds =  Arrays.asList(carpoolPost.getPrepareMembersOpenId().split(","));
        List<String> newPreMemberOpenIds = new ArrayList<>();
        newPreMemberOpenIds.addAll(preMemberOpenIds);
        newPreMemberOpenIds.removeIf(item -> item.equals(dto.getOpenId()));
        String newPreMemberOpenId = String.join(", ", newPreMemberOpenIds);
        carpoolPost.setPrepareMembersOpenId(newPreMemberOpenId);

        int i = carpoolPostMapper.updateById(carpoolPost);
        if (i<1){
            return CommonResult.failed("审核失败请联系管理员");
        }
        return CommonResult.success("审核成功");

    }

    @Override
    public IPage<CarpoolPostVo> getOwnCarpoolPost(OwnCarpoolDto pageVo) {
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);
        CarpoolPostDto carpoolPostDto = new CarpoolPostDto();
        BeanUtil.copyProperties(pageVo,carpoolPostDto);
        carpoolPostDto.setOpenId(openid);
        carpoolPostDto.setRealMembersOpenId(openid);
        Page page = new Page(pageVo.getCurrentPage(), pageVo.getPageSize());
        IPage<CarpoolPostVo> carpoolPostPageData = carpoolPostMapper.getOwnCarpoolPost(page, carpoolPostDto);
        return carpoolPostPageData;
    }

    @Override
    public CommonResult endCarpoolPost(Long carpoolPostId) {
        LambdaUpdateWrapper<CarpoolPost> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CarpoolPost::getCarpoolStatus,2);
        updateWrapper.eq(CarpoolPost::getId,carpoolPostId);
        int update = carpoolPostMapper.update(null, updateWrapper);
        if (update<1){
            return CommonResult.failed("操作失败");
        }
        return CommonResult.success("手动截止成功");
    }

    @Override
    public CommonResult cancelCarpoolPost(Long carpoolPostId) {
        CarpoolPost carpoolPost = carpoolPostMapper.selectById(carpoolPostId);
        String openid = jwtTokenUtil.getUsernameByRequest(httpServletRequest);


        if (BeanUtil.isEmpty(carpoolPost)){
            return CommonResult.failed("找不到该同乘");
        }

        if (!carpoolPost.getOpenId().equals(openid)){
            return CommonResult.failed("不是自己的同乘");
        }

        if (!carpoolPost.getRealMembersOpenId().equals("") || !carpoolPost.getPrepareMembersOpenId().equals("")){
            return CommonResult.failed("已有成员不可取消,请自行沟通");
        }

        carpoolPostMapper.deleteById(carpoolPostId);

        //commentService.list(new QueryWrapper<Comment>().lambda().eq(Comment::getCarpoolId,carpoolPostId).eq(Comment::getCommentatorOpenId,openid));
        commentService.remove(new QueryWrapper<Comment>().lambda().eq(Comment::getCarpoolId,carpoolPostId).eq(Comment::getCommentatorOpenId,openid));
        return CommonResult.success("取消成功");

    }

    public String getAccessToken() {
        String appId = "wxb4632b40969646bb";
        String appSecret = "8806f39cc7880a535c8b9522f9fc8d4c";
        String result = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }


}
